package io.yuanqi.hgtcshop.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import io.yuanqi.hgtcshop.config.RedisService;
import io.yuanqi.hgtcshop.dao.GoodsMapper;
import io.yuanqi.hgtcshop.entity.dos.Category;
import io.yuanqi.hgtcshop.entity.dos.Goods;
import io.yuanqi.hgtcshop.entity.dos.GoodsGallery;
import io.yuanqi.hgtcshop.entity.dos.GoodsSku;
import io.yuanqi.hgtcshop.entity.dto.GoodsParamsDTO;
import io.yuanqi.hgtcshop.entity.enums.ResultCode;
import io.yuanqi.hgtcshop.entity.param.GoodsSearchParams;
import io.yuanqi.hgtcshop.entity.vo.GoodReturnVO;
import io.yuanqi.hgtcshop.entity.vo.GoodsSkuVO;
import io.yuanqi.hgtcshop.entity.vo.GoodsVO;
import io.yuanqi.hgtcshop.entity.vo.SpecValueVO;
import io.yuanqi.hgtcshop.exception.ServiceException;
import io.yuanqi.hgtcshop.service.CategoryService;
import io.yuanqi.hgtcshop.service.GoodsGalleryService;
import io.yuanqi.hgtcshop.service.GoodsService;
import io.yuanqi.hgtcshop.service.GoodsSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品业务层实现
 *
 * @author pikachu
 * @since 2020-02-23 15:18:56
 */
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    /**
     * 商品相册
     */
    @Autowired
    private GoodsGalleryService goodsGalleryService;
    /**
     * 商品规格
     */
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisService redisService;


    @Override
    public GoodReturnVO queryByParams(GoodsSearchParams goodsSearchParams) {
        GoodReturnVO goodReturnVO = new GoodReturnVO();
        String key = "check_" + goodsSearchParams.getOpenId();
        Double totalPrice = new Double(0);
        List<Goods> goodsList = this.list(new LambdaQueryWrapper<Goods>().eq(Goods::getCategoryPath, goodsSearchParams.getCategoryPath()));
//        log.info("，queryByParams 查询到的结果为:{}", JSON.toJSONString(goodsList));
//        log.info(".queryByParams 返回的结果为：{}", JSON.toJSONString(goodsList));
//        List<GoodsVO> targetList = Lists.newArrayList();
//        BeanUtils.copyProperties(goodsList,targetList);
//        for (GoodsVO goods : targetList) {
//            String id = goods.getId();
//            GoodsVO goodsVO = this.getGoodsVO(id);
//            if (null != goodsVO) {
//                List<GoodsSkuVO> skuList = goodsVO.getSkuList();
//                goods.setSkuList(skuList);
//            } else {
//                log.error("goodId:{} 未查询到sku", id);
//            }
//        }
        // 标记是否已经选择
        for (Goods goods : goodsList) {
            GoodsVO goodsVO = this.getGoodsVO(goods.getId());
            if (goodsVO == null) {
                log.error("goodVO 为空。。。");
                continue;
            }

            List<GoodsSkuVO> skuList = goodsVO.getSkuList();

            if (skuList == null) {
                log.error("skuList 为空。。。");
                continue;
            }

            String value = redisService.getValue(key);
//            log.info("从redis获取到的value为:{}", value);
            HashMap<String, Boolean> skuIdAndFlagMaps = Maps.newHashMap();
            if (null != value) {
                skuIdAndFlagMaps = JSON.parseObject(value, new TypeReference<HashMap<String, Boolean>>() {
                });


//                log.info("转换后的Map为:{}", JSON.toJSONString(skuIdAndFlagMaps));
                for (GoodsSkuVO goodsSkuVO : skuList) {
                    String id = goodsSkuVO.getId();
                    Boolean b = skuIdAndFlagMaps.get(id);
                    if (null != b && b) {
                        goods.setRecommend(true);
                        break;
                    }
                }
            }
        }
        goodReturnVO.setGoodsList(goodsList);

        // 计算总价格


        String value = redisService.getValue(key);
//        log.info("从redis获取到的value为:{}", value);
        HashMap<String, Boolean> skuIdAndFlagMaps = Maps.newHashMap();
        if (null != value) {
            skuIdAndFlagMaps = JSON.parseObject(value, new TypeReference<HashMap<String, Boolean>>() {
            });

            for (Map.Entry<String, Boolean> entry : skuIdAndFlagMaps.entrySet()) {
//                log.info("计算总价开始迭代：{}", JSON.toJSONString(entry));
                String skuId = entry.getKey();
                Boolean value1 = entry.getValue();
                if (null != value1 && value1) {
                    GoodsSku skuBySkuId = goodsSkuService.getSkuBySkuId(skuId);
                    if (null != skuBySkuId) {
//                        log.info("计算总价 拿到SKUBean为:{}", JSON.toJSONString(skuBySkuId));
                        totalPrice = totalPrice + skuBySkuId.getPrice();
                    }
                }
            }
        }

        String str = String.format("%.2f",totalPrice);
        double four = Double.parseDouble(str);

        goodReturnVO.setTotalPrice(four);
        return goodReturnVO;
    }

    @Override
    public GoodsVO getGoodsVO(String goodsId) {
        //查询商品信息
        Goods goods = this.getById(goodsId);
        if (goods == null) {
            log.error("商品ID为" + goodsId + "的商品不存在");
            throw new ServiceException(ResultCode.GOODS_NOT_EXIST);
        }
        GoodsVO goodsVO = new GoodsVO();
        //赋值
        BeanUtils.copyProperties(goods, goodsVO);
        //商品id
        goodsVO.setId(goods.getId());
        //商品相册赋值
        List<String> images = new ArrayList<>();
        List<GoodsGallery> galleryList = goodsGalleryService.goodsGalleryList(goodsId);
        for (GoodsGallery goodsGallery : galleryList) {
            images.add(goodsGallery.getOriginal());
        }
        goodsVO.setGoodsGalleryList(images);
        //商品sku赋值
        List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsId);
        if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
            goodsVO.setSkuList(goodsListByGoodsId);
        }
        //商品分类名称赋值
        List<String> categoryName = new ArrayList<>();
        String categoryPath = goods.getCategoryPath();
        String[] strArray = categoryPath.split(",");
        List<Category> categories = (List<Category>) categoryService.listByIds(Arrays.asList(strArray));
        for (Category category : categories) {
            categoryName.add(category.getName());
        }
        goodsVO.setCategoryName(categoryName);

        //参数非空则填写参数
        if (CharSequenceUtil.isNotEmpty(goods.getParams())) {
            goodsVO.setGoodsParamsDTOList(JSONUtil.toList(goods.getParams(), GoodsParamsDTO.class));
        }

        return goodsVO;
    }

    public List<GoodsSkuVO> getGoodsSkuVOList(List<GoodsSku> list) {
        List<GoodsSkuVO> goodsSkuVOS = new ArrayList<>();
        for (GoodsSku goodsSku : list) {
            GoodsSkuVO goodsSkuVO = this.getGoodsSkuVO(goodsSku);
            goodsSkuVOS.add(goodsSkuVO);
        }
        return goodsSkuVOS;
    }

    public GoodsSkuVO getGoodsSkuVO(GoodsSku goodsSku) {
        //初始化商品
        GoodsSkuVO goodsSkuVO = new GoodsSkuVO(goodsSku);
        //获取sku信息
        JSONObject jsonObject = JSONUtil.parseObj(goodsSku.getSpecs());
        //用于接受sku信息
        List<SpecValueVO> specValueVOS = new ArrayList<>();
        //用于接受sku相册
        List<String> goodsGalleryList = new ArrayList<>();
        //循环提交的sku表单
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            SpecValueVO specValueVO = new SpecValueVO();
            if ("images".equals(entry.getKey())) {
                specValueVO.setSpecName(entry.getKey());
                if (entry.getValue().toString().contains("url")) {
                    List<SpecValueVO.SpecImages> specImages = JSONUtil.toList(JSONUtil.parseArray(entry.getValue()),
                            SpecValueVO.SpecImages.class);
                    specValueVO.setSpecImage(specImages);
                    goodsGalleryList =
                            specImages.stream().map(SpecValueVO.SpecImages::getUrl).collect(Collectors.toList());
                }
            } else {
                specValueVO.setSpecName(entry.getKey());
                specValueVO.setSpecValue(entry.getValue().toString());
            }
            specValueVOS.add(specValueVO);
        }
        goodsSkuVO.setGoodsGalleryList(goodsGalleryList);
        goodsSkuVO.setSpecList(specValueVOS);
        return goodsSkuVO;
    }
}
